package com.xy.shop.wechat.handler.gzh1;

import com.xy.shop.common.constant.AppConstants;
import com.xy.shop.common.utils.EncryptUtil;
import com.xy.shop.web.entity.WxUser;
import com.xy.shop.web.service.ApplyOrderService;
import com.xy.shop.web.service.BaseParamService;
import com.xy.shop.web.service.WxUserService;
import com.xy.shop.wechat.builder.TextBuilder;
import com.xy.shop.wechat.config.WxConfig;
import com.xy.shop.wechat.config.WxGzh1Config;
import com.xy.shop.wechat.handler.MsgHandler;
import com.xy.shop.wechat.service.BaseWxService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Gzh1MsgHandler
 * @Description : 功能说明 覆写MsgHandler 抽象方法handle
 * @Param:
 * @Return :
 * @Author : zyy
 * @Date : 2020/6/25 23:35
*/
@Component
public class Gzh1MsgHandler extends MsgHandler {
	
  @Autowired
  private WxGzh1Config wxGzh1Config;

  @Resource
  private ApplyOrderService applyOrderService;

  @Resource
  private BaseParamService baseParamService;

  @Resource
  private WxUserService wxUserService;

  @Resource
  private RedisTemplate redisTemplate;

  @Override
  protected WxConfig getWxConfig() {
    return this.wxGzh1Config;
  }

  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService wxMpService,
                                  WxSessionManager sessionManager) {

    BaseWxService weixinService = (BaseWxService) wxMpService;

    if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
      //TODO 可以选择将消息保存到本地
    }

    //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
    if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
            && weixinService.hasKefuOnline()) {
      return WxMpXmlOutMessage
              .TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
              .toUser(wxMessage.getFromUser()).build();
    }
    //TODO 组装回复消息
    String content = "hello 我是一个笨笨的机器人！";
    if (StringUtils.startsWithAny(wxMessage.getContent(), "填写订单", "填单") ) {
      // 获取微信用户基本信息
      String openId = wxMessage.getFromUser();
      /**查看当前用户是否存用户信息到数库*/
      WxUser wxUser =wxUserService.selectByOpendId(openId);
      if(Objects.isNull(wxUser)) {
        // 获取微信用户基本信息
        try {
          WxMpUser userWxInfo = weixinService.getUserService()
                  .userInfo(wxMessage.getFromUser(), null);
          wxUser = new WxUser();
          wxUser.setIcon(userWxInfo.getHeadImgUrl());
          int sex = 0;
          if ("男".equals(userWxInfo.getSex())) {
            sex = 1;
          } else if ("女".equals(userWxInfo.getSex())) {
            sex = 2;
          }
          wxUser.setSex(sex);
          wxUser.setOpenId(userWxInfo.getOpenId());
          wxUser.setName(userWxInfo.getNickname());
          int count = wxUserService.updateByPrimaryKeySelective(wxUser);
        } catch (WxErrorException e) {
          e.printStackTrace();
        }
      }
        String sign = applyOrderService.getOrderWriteUrl(openId,wxUser.getUid()+"");
        String url=baseParamService.selectByPrimarycode(AppConstants.BaseParam.ORDER_WRITE_URL);
        content= url+"?p="+sign;
      try {
        redisTemplate.opsForValue().set(AppConstants.RedisKey.ORDER_WRITE_SING+sign,EncryptUtil.encrypt(wxUser.getUid()+"@"+openId),2,TimeUnit.HOURS);
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }


    }
    return new TextBuilder().build(content, wxMessage, weixinService);

  }
}
